package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 操作所有预约该医生的患者业务
 */
public class RegistrationLogActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    private String loginDoctorId;

    private ListView querySetADoctorListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_log);
//        实例化
        dbOpenHelper = new DBOpenHelper(RegistrationLogActivity.this, "db_kindheartedness", null, 1);
//        获取ListView控制权
        querySetADoctorListView = findViewById(R.id.querySetADoctorListView);
//        获取当前登录医生Id
        Intent intent2 = getIntent();
        final Bundle bundle = intent2.getExtras();
        loginDoctorId = bundle.getString("loginDoctorId");
        Log.i("当前登录医生ID：", loginDoctorId);
//        查询并回显该医生相关的预约患者
        findByDoctorId(loginDoctorId);

        //        获取ListView点击事件并进行处理
        querySetADoctorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                获取选项中的HashMap对象
                HashMap<String, String> map = (HashMap<String, String>) querySetADoctorListView.getItemAtPosition(position);
                final String registrationLogId = map.get("registrationLogId");
                Log.i("获取的患者预约编号为:", registrationLogId);
                // TODO: 2022/3/27 编写取消预约
                /**
                 * 1、通过Id查询到挂号记录Id，检查预约是否已过期
                 * 2、通过挂号Id查询挂号余数+1
                 * 3、删除患者预约挂号记录
                 */
                //        建立一个对话框
//                添加一个弹出对话框
                AlertDialog alertDialog = new AlertDialog.Builder(RegistrationLogActivity.this).create();
//                设置提示
                alertDialog.setMessage("是否确认就诊？");
//                设置 确认按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//                        1、查询当前患者挂号记录是否已就诊
                        Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "id = ?", new String[]{registrationLogId}, null, null, null);
                        while (queryRegistrationLog.moveToNext()) {
                            String string = queryRegistrationLog.getString(4);
                            Integer status = Integer.valueOf(string);
                            if (status == 1) {
                                toast = ToastUtil.toastHint(toast, RegistrationLogActivity.this, "当前患者已就诊,无需再次确认！");
                                return;
                            }
                        }
//                      2、修改当前患者挂号记录的状态为已就诊
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("is_see_a_doctor","1");
                        int update = readableDatabase.update("registration_log", contentValues, "id = ?", new String[]{registrationLogId});
                        if (update == 1) {
                            toast = ToastUtil.toastHint(toast, RegistrationLogActivity.this, "当前患者已就诊！");
                            intent = new Intent(RegistrationLogActivity.this, RegistrationLogActivity.class);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, RESULT_OK);
                            finish();
                            return;
                        }
                        toast = ToastUtil.toastHint(toast, RegistrationLogActivity.this, "当前患者就诊失败,请刷新重试！");
                        return;
                    }
                });
//        设置取消按钮操作
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toast = ToastUtil.toastHint(toast, RegistrationLogActivity.this, "本次操作已取消！");
                        return;
                    }
                });
//          显示对话框
                alertDialog.show();

            }
        });


    }


    /**
     * 查询医生相关预约患者信息并回显
     *
     * @param loginDoctorId 医生Id
     */
    private void findByDoctorId(String loginDoctorId) {
        /**
         * 1、通过医生Id查询所有设置的挂号记录，提取出挂号记录Id集合、就诊日期、时间
         * 2、通过挂号记录Id查询相关的患者挂号信息，提取出患者Id、预约时间、状态
         * 3、通过患者Id查询患者信息，提取出患者姓名
         * 4、进行封装保存回显
         */
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor queryRegistrationSetting = readableDatabase.query("registration_setting", null, "doctor_id = ?", new String[]{loginDoctorId}, null, null, "registration_date desc");
//        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        while (queryRegistrationSetting.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String registrationId = queryRegistrationSetting.getString(0);
            String registrationDate = queryRegistrationSetting.getString(2);
            String registrationTime = queryRegistrationSetting.getString(3);
            map.put("setADoctorTime", registrationDate + "\n" + registrationTime);
//            通过Id查询对应患者挂号记录,可能有多个患者预约
            Cursor queryRegistrationLog = readableDatabase.query("registration_log", null, "registration_id = ?", new String[]{registrationId}, null, null, null);
            while (queryRegistrationLog.moveToNext()) {
                String registrationLogId = queryRegistrationLog.getString(0);
                map.put("registrationLogId", registrationLogId);
                String userId = queryRegistrationLog.getString(1);
                String subscribeTime = queryRegistrationLog.getString(3);
                //            年月日
                String substring = subscribeTime.substring(0, 10);
//            时分秒
                String substring2 = subscribeTime.substring(11);
                map.put("appointmentTime", substring + "\n" + substring2);
                String isSeeADoctor = queryRegistrationLog.getString(4);
                Integer status = Integer.valueOf(isSeeADoctor);
                String statusToStr = "未就诊";
                if (status == 1) {
                    statusToStr = "已就诊";
                }
                //                        判断预约是否过期
                /*String atPresentDate = DateUtil.dateString(new Date(), "yyyy-MM-dd");
                String atPresentTime = DateUtil.dateString(new Date(), "HH:mm");
//                        1、判断日期是否等于当天且时间是否过期
//                        转化字符串为时间 预约就诊日期、时间
                Date registrationDate2 = DateUtil.stringDateTime(registrationDate, "yyyy-MM-dd");
                Date registrationTime2 = DateUtil.stringDateTime(registrationTime, "HH:mm");
//                        当前日期
                Date atPresentDate2 = DateUtil.stringDateTime(atPresentDate, "yyyy-MM-dd");
//                        当前时间
                Date atPresentTime2 = DateUtil.stringDateTime(atPresentTime, "HH:mm");
                if (registrationDate.equals(atPresentDate)) { // 当天
                    if (!registrationTime2.after(atPresentTime2)) { //预约时间是否小于于当前时间
                        statusToStr = "已过期";
                    }
                }*/
                map.put("setADoctorStatus", statusToStr);
//                通过用户Id查询患者姓名
                Cursor queryUser = readableDatabase.query("user", null, "id = ?", new String[]{userId}, null, null, null);
                while (queryUser.moveToNext()) {
                    String userName = queryUser.getString(1);
                    map.put("patientName", userName);
                    resultList.add(map);
                }
            }
        }
        //        判断是否具有患者预约记录
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, RegistrationLogActivity.this, "暂时没有预约哦，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                RegistrationLogActivity.this,
                resultList,
                R.layout.query_registration_log,
                new String[]{
                        "registrationLogId",
                        "patientName", "setADoctorStatus",
                        "appointmentTime", "setADoctorTime"
                },
                new int[]{
                        R.id.registrationLogId,
                        R.id.patientName, R.id.setADoctorStatus,
                        R.id.appointmentTime, R.id.setADoctorTime
                }
        );
        querySetADoctorListView.setAdapter(simpleAdapter);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}